from mootdx.quotes import Quotes
from web.config.Config import CONFIG
from mootdx.reader import Reader

"""
历史行情客户端
"""
class HistoryQuotes:
    _instance = None
    _quotes_instance = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self, init_quotes=True, **kwargs):
        # 注意：这里我们只在第一次创建实例时初始化Quotes
        if self._quotes_instance is None and init_quotes:
            self._quotes_instance = Reader.factory(market='std', tdxdir= CONFIG['tdx']['path'])

    @property
    def quotes(self):
        # 提供对Quotes实例的访问
        if self._quotes_instance is None:
            raise RuntimeError("Quotes instance is not initialized. Call __init__ with init_quotes=True first.")
        return self._quotes_instance

    #日线
    def daily(self, symbol):
        # 代理调用Quotes实例的方法
        if self._quotes_instance is None:
            raise RuntimeError("Quotes instance is not initialized. Call __init__ with init_quotes=True first.")
        return self.rebuil_df(self._quotes_instance.daily(symbol = symbol))

        # 可以在这里添加其他代理方法...

    # 提供一个可选的方法来重新初始化Quotes实例（如果需要的话）
    #分钟线
    def minute(self, symbol):
        # 代理调用Quotes实例的方法
        if self._quotes_instance is None:
            raise RuntimeError("Quotes instance is not initialized. Call __init__ with init_quotes=True first.")
        return self.rebuil_df(self._quotes_instance.minute(symbol = symbol))

    def rebuil_df(self,df):
        if 'date' in df.index.names:
            df.reset_index(inplace=True)
        # 将 'date' 列转换为字符串格式（使用向量化操作）
        df['date'] = df['date'].dt.strftime('%Y-%m-%d %H:%M:%S')
        return df

if __name__ == '__main__':
    client = HistoryQuotes()  # 默认会初始化Quotes实例
    data = client.daily(symbol='600036')
    print("数据：")
    #print(data.to_string(header=True, sparsify=False))
    print(data.to_dict(orient='records'))

    # 如果需要，可以在后续重新初始化Quotes实例
    # client.reinit_quotes(market='std', multithread=True, heartbeat=True, bestip=True, timeout=15)

